export class SenceGrid {

  constructor(id, options = {
    width: window.innerWidth - 300,
    height: window.innerHeight - 300 
  }) {
    console.log('SenceGrid constructor')
    this.canvas = document.querySelector('#' + id)
    this.width = options.width;
    this.height = options.height;
    this.canvas.width = options.width;
    this.canvas.height = options.height;
    this.ctx = this.canvas.getContext('2d');
  }

  // 重置
  reset () {
    this.clear();
    this.draw();
  };

  draw() {
    this.drawGrid()
  }

  drawGrid() {
    const { ctx } = this;
    var griadSize = 10;
    var canvasW = ctx.canvas.width;
    var canvasH = ctx.canvas.height;
    var xNum = parseInt(canvasH/griadSize);
    var yNum = parseInt(canvasW/griadSize);

    for(var i = 0 ;i < xNum;i++){
      ctx.moveTo(0,griadSize*i-0.5);
      ctx.lineTo(canvasW,griadSize*i-0.5);
      ctx.strokeStyle = "#eee";
      ctx.stroke();
      }
      for(var j = 0 ;j < yNum;j++){
      ctx.moveTo(griadSize*j-0.5,0);
      ctx.lineTo(griadSize*j-0.5,canvasW);
      ctx.strokeStyle = "#eee";
      ctx.stroke();
    }

    //坐标X轴
    ctx.beginPath();
    var grad = 20;
    var x0 = grad;
    var y0 = canvasH-grad;
    var tra = 10;
    ctx.moveTo(x0,y0);
    ctx.lineTo(canvasW-2*grad,y0);
    ctx.lineTo(canvasW-2*grad-tra,y0-tra/2);
    ctx.lineTo(canvasW-2*grad-tra,y0+tra/2);
    ctx.lineTo(canvasW-2*grad,y0);
    ctx.strokeStyle = "#000000";
    ctx.fillStyle = "#000000";
    ctx.fill();
    ctx.stroke();
    ctx.font = "20px 微软雅黑";
    ctx.textBaseline = "middle";
    ctx.fillText("X",canvasW-2*grad,canvasH-grad);

    //坐标Y轴
    ctx.moveTo(x0,y0);
    ctx.lineTo(x0,2*grad);
    ctx.lineTo(x0-tra/2,2*grad+tra);
    ctx.lineTo(x0+tra/2,2*grad+tra);
    ctx.lineTo(x0,2*grad);
    ctx.strokeStyle = "#000000";
    ctx.fillStyle = "#000000";
    ctx.fill();
    ctx.stroke();
    ctx.font = "20px 微软雅黑";
    ctx.textAlign="center";
    ctx.fillText("Y",x0,2*grad-tra);
  }

  clear() {
    this.canvas.width = this.width;
  }

  paint() {
    this.clear();
    this.draw();
  }
}
